package com.teach3;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <pre>
 * - 广播
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2021-4-29 15:13:35
 * Version : 1.0
 * Copyright 2021 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 */
public class UDPClient {

	public static void main(String[] args) {
		try {
			// 1.创建对象
			// 构造数据报套接字并将其绑定到本地主机上任何可用的端口。
			DatagramSocket socket = new DatagramSocket();

			// 3.发送
			Thread t1 = new Thread(() -> {
				while (true) {
					try {
						Thread.sleep(1000);
						byte[] arr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).getBytes("UTF-8");
						DatagramPacket packet = new DatagramPacket(arr, arr.length,
								InetAddress.getByName("192.168.31.255"), 18000);
						socket.send(packet);
					} catch (Exception e) {
						break;
					}
				}
			});
			t1.start();
			t1.join();
			// 4.关闭资源
			 socket.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}